1   /*                        __    __  __  __    __  ___
2    *                       \  \  /  /    \  \  /  /  __/
3    *                        \  \/  /  /\  \  \/  /  /
4    *                         \____/__/  \__\____/__/.ɪᴏ
5    * ᶜᵒᵖʸʳᶦᵍʰᵗ ᵇʸ ᵛᵃᵛʳ ⁻ ˡᶦᶜᵉⁿˢᵉᵈ ᵘⁿᵈᵉʳ ᵗʰᵉ ᵃᵖᵃᶜʰᵉ ˡᶦᶜᵉⁿˢᵉ ᵛᵉʳˢᶦᵒⁿ ᵗʷᵒ ᵈᵒᵗ ᶻᵉʳᵒ
6    */
7   package io.vavr.concurrent;
8   
9   import io.vavr.CheckedFunction0;
10  import io.vavr.control.Try;
11  
12  import java.util.Random;
13  import java.util.function.Supplier;
14  
15  import static org.assertj.core.api.Assertions.fail;
16  
17  final class Concurrent {
18  
19      private static final Random RND = new Random();
20  
21      // Max wait time for results = WAIT_MILLIS * WAIT_COUNT (however, most probably it will take only WAIT_MILLIS * 1)
22      private static final long WAIT_MILLIS = 50;
23      private static final int WAIT_COUNT = 100;
24  
25      // Max sleep time to delay computation
26      private static final int SLEEP_MAX_MILLIS = 150;
27  
28      private Concurrent() {
29      }
30  
31      /**
32       * Frequently checking if something happened by testing a condition.
33       * If after {@link #WAIT_COUNT} * {@link #WAIT_MILLIS} ms nothing happened, an {@code AssertionError} is thrown.
34       *
35       * @param condition A condition.
36       */
37      static void waitUntil(Supplier<Boolean> condition) {
38          int count = 0;
39          while (!condition.get()) {
40              if (++count > WAIT_COUNT) {
41                  fail("Condition not met.");
42              } else {
43                  Try.run(() -> Thread.sleep(WAIT_MILLIS));
44              }
45          }
46      }
47  
48      /**
49       * Block current thread a random time between 0 and {@link #SLEEP_MAX_MILLIS} ms.
50       */
51      static void zZz() {
52          Try.run(() -> Thread.sleep(RND.nextInt(SLEEP_MAX_MILLIS)));
53      }
54  
55      static <T> CheckedFunction0<T> zZz(T value) {
56          return () -> {
57              zZz();
58              return value;
59          };
60      }
61  
62      static <T, X extends Throwable> CheckedFunction0<T> zZz(X exception) {
63          return () -> {
64              zZz();
65              throw exception;
66          };
67      }
68  
69      static Void waitForever() {
70          while (true) {
71              Try.run(() -> Thread.sleep(WAIT_MILLIS));
72          }
73      }
74  }